import global from './global'
import { useLoadingStore } from '@/stores/commonStore';
import { useShopStore } from '@/stores/shopStore';
const loadStore = useLoadingStore();
const shopStore = useShopStore();
export function mnavTo(url : string, nlogin : boolean = false) {
	let needLogin = nlogin || false;
	console.log("navigateTo:", url)
	//needLogin 未传递则不验证是否授权登录，页面直接跳转
	let hasLogin = uni.getStorageSync(global.IS_LOGIN) || false;
	hideLoading()
	console.log('haslogin', hasLogin, needLogin)
	if (!needLogin || hasLogin) {
		uni.navigateTo({
			url
		})
	} else {
		console.log("跳转提示：用户未登录跳转登录页面", global.CENTER_LOGIN_PAGE);
		if (!global.CENTER_LOGIN_PAGE) {
			global.CENTER_LOGIN_PAGE = true; //进入登录页面
			// #ifdef H5
			// wx.miniProgram.navigateTo({ url: '/pages/login/login/login' }) //登录
			// #endif
			// #ifndef H5
			uni.navigateTo({ url: '/pages/login/login' })
			// #endif
		}
	}
	// uni.navigateTo({
	// 	url: url
	// })
}
export function navToType(navType : string, url : string) {
	switch (navType) {
		case 'navigateTo':
			uni.navigateTo({ url });
			break;
		case 'reLaunch':
			uni.reLaunch({ url });
			break;
		case 'switchTab':
			uni.switchTab({ url });
			break;
		case 'redirectTo':
			uni.redirectTo({ url });
			break;
		default:
			uni.navigateTo({ url });
			break;
	}
}
/**
   *  函数节流
   * @param fn
   * @param awaitTime 节流间隔
   */
// export function throttle(fun, awaitTime = 2000) {
// 	console.log('throttle:', awaitTime)
// 	let startTimer = 0;
// 	//节流  一段时间只能执行一次 使用时间戳控制
// 	return (fun, ...arrAgu) => {
// 		if (typeof fun !== 'function') return
// 		const endTimer = new Date().getTime()
// 		if (endTimer - startTimer > awaitTime) {
// 			fun(...arrAgu)
// 			startTimer = new Date().getTime()
// 		}
// 	}
// }
export function throttle(fn, delay) {
	let lastCall = 0;
	return function (event) {
		const now = Date.now();
		if (now - lastCall < delay) {
			return;
		}
		lastCall = now;
		fn(event);
	};
}
/**
   *  函数防抖
   * @param fn
   * @param delay 间隔
   * const handleClick = debounce(() => {console.log('防抖后的点击');}, 300);
   */
export function debounce(fn, delay) {
	let timer = null;
	return function (...args) {
		if (timer) clearTimeout(timer);
		timer = setTimeout(() => {
			fn.apply(this, args);
		}, delay);
	};
}

/**
   *  保存事件来源等
   * @param shareMemberld
   * @param sellMemberld
   * @param share_id
   * @param event_id_1
   * const handleClick = debounce(() => {console.log('防抖后的点击');}, 300);
   */
export function checkOrg(param : any) {
	if (param.eventId || 1) {
		let timestamp = new Date().getTime();
		let expiration = timestamp + 86400000; //缓存24小时
		let dparam = {
			shareMemberId: '',
			sellMemberId: shopStore.curSellerMemberId,
			share_id: '',
			event_id_1: '',
			event_id_2: '',
			system_id: 'S039',
			expiration: expiration
		}
		let paramsData = Object.assign(dparam, param)
		console.log('paramsData+', paramsData)
		uni.setStorageSync(global.QR_PARAMS, paramsData);
	}
	// ndata.event_id_1 = params.event_id_1||'';//事件1
	// ndata.event_id_2 = params.event_id_2||'';//事件2
	// ndata.share_id = params.share_id||'';
	// ndata.shareMemberId = params.nparentMemberId || '';
	// ndata.fromSystemId = 'S039';
	// ndata.sellMemberId = params.sellMemberId || '';//推荐人
}

export function $parent(name = undefined) {
	let parent : any = this.$parent;
	// 通过while历遍，这里主要是为了H5需要多层解析的问题
	while (parent) {
		// 父组件
		if (parent.$options && parent.$options.name !== name) {
			// 如果组件的name不相等，继续上一级寻找
			parent = parent.$parent;
		} else {
			return parent;
		}
	}
	return false;
}
export function plusXing(str : string = '', frontLen : number, endLen : number) {
	str = String(str);
	var num = str.length;
	if (num == 1) {
		return '*'
	} else if (num == 2) {
		return str.substr(0, frontLen) + '*';
	} else if (num > 2) {
		let len = str.length - frontLen - endLen;
		let xing = '';
		for (let i = 0; i < len; i++) {
			xing += '*';
		}
		return str.substr(0, frontLen) + xing + str.substr(str.length - endLen);
	} else {
		return '****';
	}
}
export function toSupFixed(num, d) {
	var s = num + "";
	if (!d) d = 0;
	if (s.indexOf(".") == -1) s += ".";
	s += new Array(d + 1).join("0");
	if (new RegExp("^(-|\\+)?(\\d+(\\.\\d{0," + (d + 1) + "})?)\\d*$").test(s)) {
		var s = "0" + RegExp.$2, pm = RegExp.$1, a = RegExp.$3.length, b = true;
		if (a == d + 2) {
			a = s.match(/\d/g);
			if (parseInt(a[a.length - 1]) > 4) {
				for (var i = a.length - 2; i >= 0; i--) {
					a[i] = parseInt(a[i]) + 1;
					if (a[i] == 10) {
						a[i] = 0;
						b = i != 1;
					} else break;
				}
			}
			s = a.join("").replace(new RegExp("(\\d+)(\\d{" + d + "})\\d$"), "$1.$2");

		} if (b) s = s.substr(1);
		return Number((pm + s).replace(/\.$/, ""));
	} return num;
}
/**
   *  检查登录缓存
   * @param type 是否跳转登录页
   */
export function checkLogin(type : boolean = false) {
	const isLogin = uni.getStorageSync(global.IS_LOGIN) || false;
	if (!isLogin && type) {
		if (!global.CENTER_LOGIN_PAGE) {
			global.CENTER_LOGIN_PAGE = true; //进入登录页面
			mnavTo(`/pages/login/login`)
		}
	}
	return isLogin
}
export function trailingThrottle<T extends (...args : any[]) => void>(
	callback : T,
	delay : number
) : (...args : Parameters<T>) => void {
	let timeoutId : NodeJS.Timeout | null = null;

	const throttledFunction = (...args : Parameters<T>) => {
		if (timeoutId !== null) {
			clearTimeout(timeoutId);
		}
		timeoutId = setTimeout(() => {
			callback(...args);
		}, delay);
	};

	return throttledFunction;
}
export function getNowDate(interval:any='') {
	let date = new Date();
	let nresult :any = {};
	let year:any = date.getFullYear();
	nresult.year = year;
	let month:any = date.getMonth() + 1;
	month<10?(month='0'+month):'';
	nresult.month = month;
	let day:any = date.getDate();
	day<10?(day='0'+day):'';
	let hour:any = date.getHours();
	hour<10?(hour='0'+hour):'';
	let min:any = date.getMinutes();
	min<10?(min='0'+min):'';
	nresult.day = day;
	nresult.nmonth = [year, month].join('');
	nresult.intMonth = [year, month].join(interval);
	nresult.nday = [year, month,day].join('');
	nresult.intDay = [year, month,day].join(interval);
	nresult.intMin = [hour, min].join(interval);
	nresult.hour = hour;
	nresult.min = min;
	nresult.intMins = [year, month,day].join('-') + ' ' + [hour, min].join(':')
	nresult.nmin = [year, month,day,hour,min].join('');
	nresult.fullTime = nresult.nmin + '00';
	return nresult;
}
// 去掉字符串中的空格
export function trim(str) {
	if (!str) {
		return '';
	}
	return str.replace(/\s*/g, '');
}
/*
 * obj 转 params字符串参数
 * 例子：{a:1,b:2} => a=1&b=2
 */
export function objParseParam(obj: any) {
	let paramsStr = '';
	if (obj instanceof Array) return paramsStr;
	if (!(obj instanceof Object)) return paramsStr;
	for (const key in obj) {
		paramsStr += `${key}=${obj[key]}&`;
	}
	return paramsStr.substring(0, paramsStr.length - 1);
}
/*
 * obj 转 路由地址带参数
 * 例子：{a:1,b:2} => /pages/index/index?a=1&b=2
 */
export function objParseUrlAndParam(path: string, obj: AnyObject) {
	let url = path || '';
	let paramsStr = '';
	if (obj instanceof Array) return url;
	if (!(obj instanceof Object)) return url;
	paramsStr = this.objParseParam(obj);
	paramsStr && (url += '?');
	url += paramsStr;
	return url;
}
// 获取顶部bar高度
export function getCustomBarHeight() {
	// const e = uni.getSystemInfoSync();
	const deviceInfo = uni.getDeviceInfo()
	const systemSetting = uni.getSystemSetting()
	const appAuthorizeSetting = uni.getAppAuthorizeSetting()
	const windowInfo = uni.getWindowInfo()
	const appBaseInfo = uni.getAppBaseInfo()
	let e={...deviceInfo,...systemSetting,...appAuthorizeSetting,...windowInfo,...appBaseInfo}
	let customBar:any;
	// #ifndef MP
	// state.statusBar = Number(e.statusBarHeight);
	if (e.platform == 'android') {
		customBar = Number(e.statusBarHeight) + 50;
	} else {
		customBar = Number(e.statusBarHeight) + 45;
	}
	// #endif
	// #ifdef MP-WEIXIN
	// state.statusBar = Number(e.statusBarHeight);
	let custom = wx.getMenuButtonBoundingClientRect();
	customBar = Number(custom.bottom) + Number(custom.top) - Number(e.statusBarHeight);
	// #endif
	// #ifdef MP-ALIPAY
	// state.statusBar = Number(e.statusBarHeight);
	// customBar = Number(e.statusBarHeight) + Number(e.titleBarHeight);
	// #endif
	return customBar;
}
//判断头部高度
export function getNavTop() {
	// #ifndef H5 || APP-PLUS
	const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
	return menuButtonInfo.top - (44 - menuButtonInfo.height) / 2
	// #endif
	// eslint-disable-next-line no-unreachable
	return 0;
}

export function getSystemPhoneX(type:any=null) {
	let isneedC = false
	try{
		let cachSys = uni.getStorageSync('sysinfo').model||'';
		let clientType = cachSys?cachSys:uni.getDeviceInfo().model||'';
		const mobileType = type || ["iPhone X","iPhone 11","iPhone 12","iPhone 13","iPhone 14", "iPhone 15", "iPhone 16","iPhone 17","iPhone 18","iPhone 19","iPhone 20"]
		if(Array.isArray(mobileType)){
			for(let v of mobileType){
				if(clientType.indexOf(v) > -1){
					isneedC=true
					break
				}
			}
		}else if(typeof(mobileType)=='string') {
			isneedC = clientType.indexOf(mobileType) > -1 ? true : false
		}
		return isneedC;
	}catch(e){
		//TODO handle the exception
		console.log('获取手机型号getSystemPhoneX错误',e)
		return false;
	}
	

}
/*
 * 苹果x以上底部增加高度
 * 
 */
export function transStyleNum(num:any=0) {
	let isx = getSystemPhoneX(),cnum=0;
	cnum = isx? (num + 30):num;
	return cnum
}

export function getCurRoute() {
	const routes = getCurrentPages();
	console.log('home-routes',routes)
	return routes[routes.length - 1].route;
}
export function showLoading(info : any = { title: '', time: 0, color: '#fff', maskColor: false, mask: false }) {
	loadStore.showLoading(info)
}
export function hideLoading() {
	loadStore.hideLoading()
}
export function getTime(value) {
	// console.log("value:", value)
	
	if (!value) {
		// console.log("时间格式化错误请检查utils文件下js方法：getTime")
		return new Date();
	}
	let temp = value.substring(0, 4);
	temp += '-' + value.substring(4, 6);
	temp += '-' + value.substring(6, 8);
	temp += ' ' + value.substring(8, 10);
	temp += ':' + value.substring(10, 12);
	temp += ':' + value.substring(12, 14);
	// console.log('getTime----------temp',temp)
	let date = new Date(temp.replace(/-/g, "/"))
	// let time = Date.parse(date); //获得时间戳
	let time = date.getTime(); //获得时间戳
	let hour = date.getHours();
	let min = date.getMinutes();
	let stime = (hour<10?'0' + hour : hour) + ':' + (min<10?'0' + min : min);
	let dateObj = {
		year: date.getFullYear(), //获得年
		month: date.getMonth() + 1, //获得月
		day: date.getDate(), //获得日
		hour: hour, //获得小时
		min: min, //获得分钟
		seconds: date.getSeconds(), //获得秒
		stime: stime,
		date: date,
		time: time
	}
	console.log("getTime:", dateObj)
	return dateObj;
}

export function vPhone(number){
	var reg=11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/;
	return reg.test(number)
}

export function transPhones(number){
	let num = ''
	if(vPhone(number)){
		number = number + '';
		num = number.substr(0,3) + "****" + number.substr(7);
	}
	return num
}
export function transFullTimes(value){
	if(!value){
		return ''
	}
	let yy = value.substring(0, 4);
	let mm = value.substring(4, 6);
	let dd = value.substring(6,8);
	let tt = value.substring(8,12)
	let uday = yy + mm + dd
	let result = {
		year:yy,
		month:mm,
		day:dd,
		uday:uday,
		mtime:tt
	}
	return result
}
export default {
	mnavTo,
	throttle,
	checkOrg,
	showLoading,
	hideLoading,
	plusXing,
	toSupFixed,
	trailingThrottle,
	checkLogin,
	trim,
	objParseParam,
	objParseUrlAndParam,
	getCustomBarHeight,
	getNavTop,
	getNowDate,
	getSystemPhoneX,
	getCurRoute,
	transStyleNum,
	getTime,
	vPhone,
	transPhones,
	transFullTimes
}